package zmee.wfs.formplugin;

import json.JSONObject;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.utils.StringUtils;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.user.UserServiceHelper;
import kd.bos.workflow.design.plugin.AbstractWorkflowPlugin;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.EventObject;

/**
 * @Author: zyj
 * @Date: 2023/7/10 16:45
 * @Description: 审批处理页面: 由OA进入审批页面修改OA待阅状态
 */
public class OATaskDealBillPlugin extends AbstractWorkflowPlugin {

    private static Log logger = LogFactory.getLog(OATaskDealBillPlugin.class);

    @Override
    public void beforeBindData(EventObject e) {
        super.beforeBindData(e);
        // 获取链接上的参数, 如果messagetype为sendMessage,代表是传阅的,则进入就清OA的待阅
        String messagetype = this.getView().getFormShowParameter().getCustomParam("messagetype");
        if ("sendMessage".equals(messagetype)) {
            // 流程实例id
            String flowId = this.getView().getFormShowParameter().getCustomParam("flowid");
            if (flowId == null) {
                this.getView().showTipNotification("清除OA传阅消息失败！！，原因：流程实例id为空");
                return;
            }
            // 存放传阅已阅的请求参数
            net.sf.json.JSONObject requestJson = new net.sf.json.JSONObject();
            // 获取当前用户ID
            long userId = UserServiceHelper.getCurrentUserId();
            // 查询当前用户人员
            DynamicObject user = BusinessDataServiceHelper.loadSingle(userId, "bos_user");
            // 获取当前用户的用户名
            String username = user.getString("username");
            // 存放OA接口地址
            String url = null;
            QFilter qFilter = new QFilter("number", QCP.equals, "OA");
            //获取消息渠道待办接口地址
            DynamicObject dynobj= BusinessDataServiceHelper.loadSingle("msg_channel","zmee_createtodo", new QFilter[]{qFilter});
            if(dynobj != null){
                url = dynobj.getString("zmee_createtodo");
            }
            if(StringUtils.isEmpty(url)){
                this.getView().showTipNotification("清除OA传阅消息失败！！，原因：OA消息渠道的待办接口地址未维护，请检查并维护！（路径：系统管理-消息平台-消息渠道）");
                return;
            }
            QFilter qFilter1 = new QFilter("zmee_flowid", QCP.equals, flowId);
            QFilter qFilter2 = new QFilter("name", QCP.equals, "sendMessage");
            // 设置过滤条件 根据传阅的消息类型和流程实例id查询 oa统一代办日志
            DynamicObject[] oaLogs = BusinessDataServiceHelper.load("zmee_log_oapush", "zmee_request, zmee_receiver", new QFilter[]{qFilter1, qFilter2});
            if (oaLogs == null || oaLogs.length == 0) {
                this.getView().showTipNotification("清除OA传阅消息失败！！，原因：未找到该条oa传阅日志,具体请去oa统一代办日志中查询情况！");
                return;
            }
            for (DynamicObject oaLog : oaLogs) {
                // 获取日志的接收人
                String receiver = oaLog.getString("zmee_receiver");
                // 由于传阅可能有多个接收人，所以按,分割 获得接收人字符串数组
                String[] splitReceivers = receiver.split(",");
                for (String splitReceiver : splitReceivers) {
                    // 如果当前用户是接收人的话
                    if (username.equals(splitReceiver)) {
                        // 获取推送接口请求
                        String request = oaLog.getString("zmee_request");
                        // 将请求转换为json对象
                        JSONObject parse = JSONObject.parseObject(request);
                        // 异构系统标识
                        requestJson.put("syscode", parse.getString("syscode"));
                        // 流程实例id
                        requestJson.put("flowid", parse.getString("flowid"));
                        // 流程标题
                        requestJson.put("requestname", "已阅：" + parse.getString("requestname"));
                        requestJson.put("workflowname", "优采云待办");
                        // PC地址
                        requestJson.put("pcurl", parse.getString("pcurl"));
                        // APP地址
                        requestJson.put("appurl", parse.getString("appurl"));
                        // 流程处理状态  4：办结
                        requestJson.put("isremark", "4");
                        // 流程查看状态  1：已读
                        requestJson.put("viewtype", "1");
                        // 创建人
                        requestJson.put("creator", parse.getString("creator"));
                        // 接收人账号
                        requestJson.put("receiver", username);
                        // 时间戳字段
                        requestJson.put("receivets", String.valueOf(System.currentTimeMillis()));
                        logger.info("OA已阅请求：requestJson:"+requestJson.toString());
                        // 调用OA接口
                        String returnResult = postData2ofs(url, requestJson.toString());
                        break;
                    }
                }
            }
        }
    }

    public String postData2ofs(String posturl, String param) {
        OutputStreamWriter out = null;
        BufferedReader in = null;
        String result = "";

        try {
            URL realUrl = new URL(posturl);
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            out.write(param);
            out.flush();

            String line;
            for(in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); (line = in.readLine()) != null; result = result + line) {
            }

            net.sf.json.JSONObject object = net.sf.json.JSONObject.fromObject(result);
            String returnResult = object.toString();
            String var11 = returnResult;
            return var11;
        } catch (Exception var21) {
            logger.error("zmee.cloud.bos.OAMessageServiceHandler,发送 POST请求出现异常！", var21.getMessage());
        } finally {
            try {
                if (out != null) {
                    out.close();
                }

                if (in != null) {
                    in.close();
                }
            } catch (IOException var20) {
                var20.printStackTrace();
            }

        }

        return null;
    }
}
